package servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tool.Cache;
import tool.DataFileHandler;

import applet.energy.EnergyHeight;
import applet.energy.ImageCanvas;
import applet.molecule.Atom;
import applet.molecule.MoleculeNet;

/**
 * This servlet deal with data transforming event.
 */
@SuppressWarnings("serial")
public class DataTransformer extends HttpServlet {

	/** 
	 * Constructor of the object.
	 */
	public DataTransformer() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method mainly deal with the file data request event. It will response
	 * the request, and send the client the data according to request file type.
	 * <p/>
	 * Currently, the valid file type is "energy" for energy height data and 
	 * "molecule" for atom's 3D positions of molecule.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");

		String realPath = request.getSession().getServletContext().getRealPath(
				"");
		String parsedFolder = realPath + DataFileHandler.DATA_FOLDER
				+ DataFileHandler.DATA_PARSED;
		String type = request.getParameter("type");

		String select = request.getParameter("select");
		if (type.equals(EnergyHeight.REQUEST_TYPE)) {
			float[][] list = Cache.getInstance().fetch(
					request.getParameter("filename"));

			PrintWriter writer = new PrintWriter(response.getOutputStream());

			for (int x = 0; x < ImageCanvas.POINT_NUM; x++) {
				for (int y = 0; y < ImageCanvas.POINT_NUM; y++) {
					writer.println(x);
					writer.println(y);
					writer.println(list[ImageCanvas.POINT_NUM - y - 1][x]);
					writer.flush();
				}
			}
			writer.close();
		} else if (type.equals(MoleculeNet.GROUP_REQUEST_TYPE)) {
			PrintWriter writer = new PrintWriter(response.getOutputStream());

			int x = Integer.parseInt(request.getParameter("x"));
			int y = Integer.parseInt(request.getParameter("y"));
			File dir = new File(parsedFolder + "/" + select + "/" + x + "x" + y);

			if (!dir.exists()) {
				writer.println(0);
				writer.println("end");

				writer.flush();
				writer.close();

				return;
			}

			int count = dir.list().length;
			writer.println(count);

			List<Atom> list = null;
			String stream = null;
			for (int i = 0; i < count; i++) {
				list = DataFileHandler.parseAtomFile(dir.getAbsolutePath()
						+ "/" + i, "0");
				if (list == null) {
					break;
				}

				writer.println(list.size());
				for (Atom b : list) {
					stream = b.element + " " + b.x + " " + b.y + " " + b.z;
					writer.println(stream);
					writer.flush();
				}
			}

			writer.println("end");
			writer.close();
		} else if (type.equals(MoleculeNet.NON_GROUP_REQUEST_TYPE)) {
			PrintWriter writer = new PrintWriter(response.getOutputStream());

			int x = Integer.parseInt(request.getParameter("x"));
			int y = Integer.parseInt(request.getParameter("y"));
			int index = Integer.parseInt(request.getParameter("index"));
			File dir = new File(parsedFolder + "/" + select + "/" + x + "x" + y + "/" + index);

			if (!dir.exists()) {
				writer.println(0);
				writer.println("end");

				writer.flush();
				writer.close();

				return;
			}

			int count = dir.list().length;
			writer.println(count);

			List<Atom> list = null;
			String stream = null;
			for (int i = 0; i < count; i++) {
				list = DataFileHandler.parseAtomFile(dir.getAbsolutePath(), "" + i);
				if (list == null) {
					break;
				}

				writer.println(list.size());
				for (Atom b : list) {
					stream = b.element + " " + b.x + " " + b.y + " " + b.z;
					writer.println(stream);
					writer.flush();
				}
			}

			writer.println("end");
			writer.close();
		} else {
			throw new RuntimeException("invalid request type " + type);
		}
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
